import 'package:app/constants/http_constants.dart';
import 'package:app/http/api_service.dart';
import 'package:app/models/project.dart';
import 'package:app/models/response.dart';
import 'package:app/widgets/wrappers/date_picker_wrapper.dart';
import 'package:app/widgets/modal.dart';
import 'package:calendar_date_picker2/calendar_date_picker2.dart';
import 'package:creato_ui/creato_ui.dart';
import 'package:date_format/date_format.dart';
import 'package:flutter/material.dart';

class CreateOrEditProjectPage extends StatefulWidget {
  const CreateOrEditProjectPage({super.key});

  @override
  State<CreateOrEditProjectPage> createState() => _CreateOrUpdateProjectState();
}

class _CreateOrUpdateProjectState extends State<CreateOrEditProjectPage> {
  Project project = Project();
  final Map<double, String> statusMap = {0: "未启动", 1: "进行中", 2: "已结束"};

  String formatTime(DateTime value) {
    return formatDate(value, [yyyy, '-', mm, '-', dd]);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: CustomScrollView(
        slivers: [
          _buildAppbar(),
          _buildContent(),
          SliverToBoxAdapter(
            child: Padding(
              padding:
                  const EdgeInsets.symmetric(horizontal: 47.5, vertical: 12),
              child: CreatoButton(
                text: "确定",
                onPressed: () async {
                  ResponseData result =
                      await ApiService(context).createOrUpdateProject(project);
                  if (result.code == HttpConstants.SUCCEED_CODE) {
                    Navigator.pop(context, true);
                  }
                },
              ),
            ),
          )
        ],
      ),
    );
  }

  Widget _buildAppbar() {
    return SliverAppBar(
      pinned: true,
      expandedHeight: 200,
      flexibleSpace: FlexibleSpaceBar(
        title: const Text(
          "创建项目",
          style:
              TextStyle(color: Color(0xFF00366B), fontWeight: FontWeight.w600),
        ),
        expandedTitleScale: 1,
        background: Image.asset(
          "assets/images/project_bg.png",
          fit: BoxFit.cover,
        ),
      ),
    );
  }

  Widget _buildContent() {
    double itemGap = 12;
    return SliverPadding(
      padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 35),
      sliver: SliverList.list(
        children: [
          _buildItem(
              "项目信息",
              TextField(
                decoration: const InputDecoration(
                    hintText: "输入项目名称",
                    contentPadding: EdgeInsets.symmetric(horizontal: 0)),
                onChanged: (value) {
                  project.pjname = value;
                },
              ),
              true),
          SizedBox(
            height: itemGap,
          ),
          _buildItem(
              "项目状态",
              InkWell(
                splashColor: Colors.transparent,
                highlightColor: Colors.transparent,
                onTap: () {
                  FocusScope.of(context).requestFocus(FocusNode());
                  Modal.bottomSheet(context,
                      child: CreatoActionSheet(
                          title: const Text("项目状态"),
                          actions: [
                            CreatoActionSheetAction(
                                child: const Text("未启动"),
                                onTap: () {
                                  setState(() {
                                    project.status = 0;
                                  });
                                  Navigator.pop(context);
                                }),
                            CreatoActionSheetAction(
                                child: const Text("进行中"),
                                onTap: () {
                                  setState(() {
                                    project.status = 1;
                                  });
                                  Navigator.pop(context);
                                }),
                            CreatoActionSheetAction(
                                child: const Text("已结束"),
                                onTap: () {
                                  setState(() {
                                    project.status = 2;
                                  });
                                  Navigator.pop(context);
                                }),
                          ]));
                },
                child: SizedBox(
                    height: 54,
                    child: Row(
                      children: [
                        Expanded(
                            child: Text(
                          statusMap[project.status] ?? "请选择项目状态",
                          style: TextStyle(
                              color: statusMap[project.status] == null
                                  ? Colors.grey
                                  : Colors.black),
                        )),
                        Image.asset("assets/images/user_icon_right.png")
                      ],
                    )),
              ),
              false),
          SizedBox(
            height: itemGap,
          ),
          _buildItem(
              "项目号",
              TextField(
                decoration: const InputDecoration(
                    hintText: "输入项目名称",
                    contentPadding: EdgeInsets.symmetric(horizontal: 0)),
                onChanged: (value) {
                  project.projNo = value;
                },
              ),
              false),
          SizedBox(
            height: itemGap,
          ),
          _buildItem(
              "项目周期",
              InkWell(
                splashColor: Colors.transparent,
                highlightColor: Colors.transparent,
                onTap: () {
                  FocusScope.of(context).requestFocus(FocusNode());
                  Modal.bottomSheet(
                    context,
                    child: DatePickerWidgetWrapper(
                      calendarType: CalendarDatePicker2Type.range,
                      defaultValue:
                          project.startTime != null && project.endTime != null
                              ? [project.startTime!, project.endTime!]
                              : [],
                      onConfirm: (value) {
                        setState(() {
                          project.startTime = value[0];
                          project.endTime = value[1];
                        });
                      },
                    ),
                  );
                },
                child: SizedBox(
                    height: 54,
                    child: Row(
                      children: [
                        Expanded(
                            child: Text(
                                project.startTime != null &&
                                        project.endTime != null
                                    ? "${formatTime(project.startTime!)} 至 ${formatTime(project.endTime!)}"
                                    : "请选择项目周期",
                                style: TextStyle(
                                    color: statusMap[project.status] == null
                                        ? Colors.grey
                                        : Colors.black))),
                        Image.asset("assets/images/user_icon_right.png")
                      ],
                    )),
              ),
              false),
          SizedBox(
            height: itemGap,
          ),
          _buildItem(
              "项目目标",
              TextField(
                decoration: const InputDecoration(
                    hintText: "输入项目名称",
                    contentPadding: EdgeInsets.symmetric(horizontal: 0)),
                onChanged: (value) {
                  setState(() {
                    project.target = value;
                  });
                },
              ),
              false)
        ],
      ),
    );
  }

  Widget _buildItem(String title, Widget child, bool isRequired) {
    return Column(
      children: [
        CreatoLabelVerticalListTile(
          label: title,
          isRequired: isRequired,
          gap: 0,
          child: child,
        ),
        const SizedBox(
          height: 2,
        ),
        const CreatoDivider()
      ],
    );
  }
}
